import { TeamOrder, WayInfo } from "../../config/play_def"
import { CommonBuff } from "../../config/role_def"
import { Control_Listen, PlayGround_Listen } from "../../config/ui_def";

cc.Class({
    extends: cc.Component,

    properties: {
        choose:0,   // 当前选择角色
        attacking: false,
        hp_ani_switch:false,            // 血条检测
        hp_ani:0,                       // 生命值动画值
    },
    initInfo(){
        // TeamOrder 是 53124 就是user部分的队列
        this.roleScript = {}        // 角色炮塔脚本
        this.buff = []              // Buff  列表
        this.buffDict = {}          // Buff  对应每个Buff效果
        this.wall_pos = {}
    },
    // 更新信息
    updateInfo(){
        this.buff = []              // Buff  列表
        this.buffDict = {}          // Buff  对应每个Buff效果
        this.hitBarInit()
    },
    // 角色模型初始化
    roleInit(){
        let team = gg.data.user_team
        for(let i = 0;i < team.length; i++){
            let script_index = TeamOrder.indexOf(team[i].order)
            this.roleScript[script_index + 1].updateInfo(team[i])
        }
        if(team.length){
            for(let i = 0;i < WayInfo.col;i++){
               let res = this.roleUp(i + 1)
               if(res){
                   break
               }
            }
        }else{
            he.error("team,用户数据错误")
        }
    },
    hitBarInit(){
        this.left_hit_node = this.node.getChildByName("LeftHit")
        this.right_hit_node = this.node.getChildByName("RightHit")
        this.left_hit_node.scale = zoom_scale
        this.left_hit_widget = this.left_hit_node.getComponent(cc.Widget)
        this.right_hit_widget = this.right_hit_node.getComponent(cc.Widget)
        
        this.left_hit_model = this.left_hit_node.getComponent(sp.Skeleton)
        this.right_hit_model = this.right_hit_node.getComponent(sp.Skeleton)
        this.left_hit_widget.left = -(this.left_hit_node.width/2)
        this.right_hit_widget.right = -(this.left_hit_node.width/2 )
        this.left_hit_widget.updateAlignment()
        this.right_hit_widget.updateAlignment()
        this.left_hit_node.active = false
        this.right_hit_node.active = false
    
        // 血条
        let hp_parent_node = this.disk_spine.node.parent.getChildByName("hpCover")
        this.hp_ani_sprite = hp_parent_node.getChildByName("Ani").getComponent(cc.Sprite)
        this.hp_now_sprite = hp_parent_node.getChildByName("Now").getComponent(cc.Sprite)
        this.updateHp()
    },
    // 监听
    diskAniListen(){
        if(this.disk_spine){
            this.disk_spine.setCompleteListener((trackEntry) => {
                var animationName = trackEntry.animation ? trackEntry.animation.name : "";
                this.diskListenComTag(animationName)
            });
        }
    },
    diskListenComTag(ani){
        switch (ani) {
            case 'hit':
                this.disk_spine.setAnimation(0,'stand_by',true)
                break
        }
    },
    hitAni(){
        this.hp_now_sprite.fillRange = gg.data.hp / gg.data.hpMax
        this.hp_ani_switch = true
        this.left_hit_node.active = true
        this.right_hit_node.active = true
        this.left_hit_model.setAnimation(0,'hit',false)
        this.right_hit_model.setAnimation(0,'hit',false)
        this.disk_spine.setAnimation(0,'hit',false)
    },
    // 角色走一步
    roleUp(order){
        let team_order = TeamOrder.indexOf(order) + 1
        if(!this.roleScript[team_order].lastScript){
            return false
        }
        this.choose = team_order//切换选中的角色
        for(let i = 0; i < WayInfo.col; i++){
            let index = i + 1
            if( team_order == index ){
                this.roleScript[index].forwardRole()
                if(this.roleScript[index].role_id){
                    gg.eventManager.emit("topInfo",PlayGround_Listen.UPDATE_AVATAR,this.roleScript[index].role_id)
                }
            }else{
                this.roleScript[index].backRole()
            }
        }      
        return true     
    },
    // 交互攻击
    turnAttack(event){
        if(!this.choose){//判断选中的角色是否为空
            return 
        }
        if(!gg.data.status){
            if(!gg.data.pass_index){
                gg.data.startPass()
                gg.eventManager.emit("startGuide",Control_Listen.CLOSE_START_GUIDE)
            }else{
                this.stopAttack()
                return
            }
        }
        if(!this.attacking){
            this.attacking = true
        }
        if(this.choose && this.roleScript[this.choose]){
            this.roleScript[this.choose].handTurnAttack(event.getLocation())
        }
    },
    // 停止攻击
    stopAttack(){
        if(!this.choose){
            return 
        }
        this.attacking = false
        if(this.choose && this.roleScript[this.choose]){
            this.roleScript[this.choose].stopAttack()
        }
    },
    // 添加Buff
    addBuff(param) {
        if (param) {
            if (param.uid) {
                for (let i = 0; i < this.buff.length; i++) {
                    if (this.buff[i].uid == param.uid) {
                        this.buff[i] = param
                        return this.updateBuff(param.key)
                    }
                }
                this.buff.push(param)
                return this.updateBuff(param.key)
            } else {
                this.buff.push(param)
                return this.updateBuff(param.key)
            }
        }
    },
    // 获取Buff 统计值
    getBuff(key) {
        if (this.buffDict && (this.buffDict[key] || this.buffDict[key] === 0)) {
            return this.buffDict[key]
        } else {
            return this.updateBuff(key)
        }
    },
    // 获取Buff信息
    getBuffInfo(index, type, param) {
        switch (type) {
            case GetBuffType.INDEX:
                if (this.buff[index]) {
                    return this.buff[index]
                }
            case GetBuffType.UID:
                for (let i = 0; i < this.buff.length; i++) {
                    if (this.buff[i].uid == index) {
                        return this.buff[i]
                    }
                }
                break
            case GetBuffType.KAU:
                for (let i = 0; i < this.buff.length; i++) {
                    if (this.buff[i].uid == index && this.buff[i].key == param) {
                        return this.buff[i]
                    }
                }
                break
            case GetBuffType.KEY:
            default:
                for (let i = 0; i < this.buff.length; i++) {
                    if (this.buff[i].key == index) {
                        return this.buff[i]
                    }
                }
                break
        }
        return null
    },
    // 获得并删除
    getDelBuffInfo(id, type) {
        if (!type) {
            type = 1
        }
        let res = null
        switch (type) {
            case GetBuffType.INDEX:
                res = this.buff.splice(id, id + 1)
                this.buff.splice(id, 1)
                break
            case GetBuffType.UID:
                for (let i = 0; i < this.buff.length; i++) {
                    let buff = this.buff[i]
                    if (buff.uid && buff.uid == id) {
                        res = this.buff.splice(i, i + 1)
                        this.buff.splice(i, 1)
                        break
                    }
                }
                break
            case GetBuffType.KEY:
                for (let i = 0; i < this.buff.length; i++) {
                    let buff = this.buff[i]
                    if (buff.key && buff.key == id) {
                        res = this.buff.splice(i, i + 1)
                        this.buff.splice(i, 1)
                        break
                    }
                }
                break
        }
        this.updateBuff()
        if (res) {
            return res[0]
        }
        return res
    },
    // 获取同种类型Buff类型
    getBuffList(key) {
        let list = []
        for (let i = 0; i < this.buff.length; i++) {
            if (this.buff[i].key == key) {
                list.push(this.buff[i])
            }
        }
        return list
    },
    // 删除Buff
    delBuff(id, type) {
        // type 1 index, type 2 uid , type3 key
        // 索引，唯一，类型
        if (!type) {
            type = 1
        }
        switch (type) {
            case 1:
                this.buff.splice(id, 1)
                break
            case 2:
                for (let i = 0; i < this.buff.length; i++) {
                    let buff = this.buff[i]
                    if (buff.uid && buff.uid == id) {
                        this.buff.splice(i, 1)
                        break
                    }
                }
                break
            case 3:
                for (let i = this.buff.length - 1; i >= 0; i--) {
                    let buff = this.buff[i]
                    if (buff.key && buff.key == id) {
                        this.buff.splice(i, 1)
                        break
                    }
                }
                break
        }
        this.updateBuff()
    },
    // 更新Buff
    updateBuff(key) {
        if (!this.buff) {
            return
        }
        
        if (key) {
            let count = 0
            for (let i = 0; i < this.buff.length; i++) {
                if (this.buff[i].key == key) {
                    count += this.buff[i].value
                }
            }
            let start_buff = false
            if(!this.buffDict[key] && count){
                start_buff = true
            }
            this.buffDict[key] = count
            this.startBuff(key,count)
            if (key && this.buffDict) {
                if (this.buffDict[key] === undefined) {
                    this.buffDict[key] = 0
                    return 0
                }
                return this.buffDict[key]
            }
            return 0
        } else {
            let buffDict = {}
            for (let key in this.buffDict) {
                buffDict[key] = 0
            }
            for (let i = 0; i < this.buff.length; i++) {
                if (buffDict[this.buff[i].key]) {
                    buffDict[this.buff[i].key] += this.buff[i].value
                } else {
                    buffDict[this.buff[i].key] = this.buff[i].value
                }
            }
            this.buffDict = buffDict
            return 0
        }
    },
    startBuff(key,count){
        switch(key){
            case CommonBuff.HP_MAX_UP:
                gg.data.updateHpMax()
            break
        }
    },
    // Buff清空后
    overBuff(buff) {
        this.updateBuff(buff.key)
        switch (buff.key) {
            case CommonBuff.SwapRole:
                gg.control.roleScript[buff.order].swapIn(buff.role)
            break
            case CommonBuff.CreateBullet:
                let random_boid = gg.boidsManager.getBoid()
                if(!random_boid){
                    return 
                }
                if(buff.num <= 0){
                    return
                }else{
                    buff.num -= 1
                    buff.time = buff.tcount
                    this.addBuff(buff)
                }
                let dir
                if(random_boid && random_boid.canAttack()){
                    let apos = random_boid.node.convertToWorldSpaceAR(cc.Vec2.ZERO)
                    let tpos = buff.pos
                    dir = apos.sub(tpos).normalizeSelf()
                }else{
                    dir = cc.Vec2.ZERO
                }
                let create_bullet = {
                    pos : buff.pos,
                    damege: parseInt(buff.param[6]),                // 伤害
                    script:buff.param[0],            // 子弹脚本
                    dir: dir,
                    // voice: this.info.bulletVoice,       // 子弹声音
                    through: new Boolean(buff.param[3]),
                    speed: parseInt(buff.param[5]),       // 子弹速度
                    collider: buff.param[2], // 碰撞形状
                    style:{                             // 子弹样式
                        skin: buff.param[4],
                        url:'spine/bullet/' + buff.param[1],
                        type:sp.SkeletonData
                    },
                    effect:[],                          // 子弹效果
                    attack_from: buff.attack_from,
                }
                create_bullet = gg.bulletManager.addBulletEffect(create_bullet,buff.extra)
                gg.bulletManager.addBullet(create_bullet)
            break
            case CommonBuff.CreateDecorate:
                let random_d_boid = gg.boidsManager.getBoid()
                if(!random_d_boid){
                    return 
                }
                if(buff.num <= 0){
                    return
                }else{
                    buff.num -= 1
                    buff.time = buff.tcount
                    this.addBuff(buff)
                }
                
                let create_Decorate = {
                    pos : buff.pos,
                    damege: parseInt(buff.param[6]),                // 伤害
                    script:buff.param[0],            // 子弹脚本
                    dir: cc.v2(0,1),
                    // voice: this.info.bulletVoice,       // 子弹声音
                    through: new Boolean(buff.param[3]),
                    speed: parseInt(buff.param[5]),       // 子弹速度
                    collider: buff.param[2], // 碰撞形状
                    style:{                             // 子弹样式
                        skin: buff.param[4],
                        url:'spine/bullet/' + buff.param[1],
                        type:sp.SkeletonData
                    },
                    effect:[],                          // 子弹效果
                    attack_from: buff.attack_from,
                }
                create_Decorate = gg.bulletManager.addBulletEffect(create_Decorate,buff.extra)
                gg.bulletManager.addBullet(create_Decorate)
                break
        }
    },
    // 血条检测
    aniHp(){
        if(gg.data.hp != this.hp_ani){
            if(this.hp_ani > gg.data.hp){
                this.hp_ani -= 1
            }else if(this.hp_ani < gg.data.hp){
                this.hp_ani += 1
            }else{
                this.hp_ani_switch = false
            }
            this.updateHp(this.hp_ani)
        }
    },
    // 帧检测Buff
    checkBuff(dt) {
        if (this.buff && this.buff.length) {
            let buffList = []
            for (let i = this.buff.length - 1; i >= 0; i--) {
                if (this.buff[i].time > 0) {
                    this.buff[i].time -= dt
                }
                if (this.buff[i].time <= 0) {
                  buffList.push(this.buff[i])
                  this.buff.splice(i, 1)
                }
            }
            if (buffList && buffList.length) {
                for (let i = 0; i < buffList.length; i++) {
                    this.overBuff(buffList[i])
                }
            }
        }
    },
    // 直接更新血条
    updateHp(hpNum){
        if(hpNum){
            this.hp_ani_sprite.fillRange = hpNum / gg.data.hpMax
        }else{
            this.hp_ani = gg.data.hp
            this.hp_ani_sprite.fillRange = 1
            this.hp_now_sprite.fillRange = 1
        }
    },
    checkHp(dt){
        if(this.hp_ani_switch){
            this.aniHp(dt)
        }
    }
});
